package com.donzell.controller;

import java.util.Arrays;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.donzell.auth.SessionHelper;
import com.donzell.dao.UserRepository;
import com.donzell.exception.LoginErrorException;
import com.donzell.model.bean.User;


@RestController
@RequestMapping(value="/auth", produces = "application/json;charset=UTF-8")
public class AuthController {

	@Autowired
	private UserRepository userRepository;

	@RequestMapping(value = "/sign/in", method = RequestMethod.POST)
	public User login(@RequestParam("username") String username,
			@RequestParam("password") String password, HttpSession session) {
		User user = userRepository.findByUsername(username);
		if (user == null) {
			throw new RuntimeException("用户名不存在");
		}
		byte[] pw = null;
		try {
			pw = Hex.decodeHex(DigestUtils.md5Hex(password).toCharArray());
		} catch (DecoderException e) {
			throw new RuntimeException("密码异常");
		}
//		if (!Arrays.equals(user.getPassword(), pw)) {
//			throw new RuntimeException("密码错误");
//		}

		session.setAttribute(SessionHelper.UserHandler, user);
		return user;
	}

	@RequestMapping(value = "/sign/out")
	public ResponseEntity<Object> loginOut(HttpSession session) {
		session.removeAttribute(SessionHelper.UserHandler);
		return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
	}

	@RequestMapping(value = "/sign/info")
	public User loginInfo(HttpSession session) {
		return (User) session.getAttribute(SessionHelper.UserHandler);
	}
}
